package cn.antho.basic.service.impl;

import cn.antho.basic.config.BussinessException;
import cn.antho.basic.constant.BaseConstant;
import cn.antho.basic.dto.EmailCodeDto;
import cn.antho.basic.service.IRegisterService;
import cn.antho.basic.util.MD5Utils;
import cn.antho.basic.util.StrUtils;
import cn.antho.user.domain.Logininfo;
import cn.antho.user.domain.User;
import cn.antho.user.dto.EmailRegisterDto;
import cn.antho.user.dto.PhoneRegisterDto;
import cn.antho.user.mapper.LogininfoMapper;
import cn.antho.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        // 验证参数
        this.verifyPhoneParam(dto);
        // 转换
        User user = PhoneDtoConvertUser(dto);
        Logininfo logininfo = userConvertLogininfo(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public void emailRegister(EmailRegisterDto dto) {
        // 验证参数
        this.verifyEmailParam(dto);
        // 转换
        User user = EmailDtoConvertUser(dto);
        Logininfo logininfo = userConvertLogininfo(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private Logininfo userConvertLogininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User PhoneDtoConvertUser(PhoneRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        String saltPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(saltPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    private User EmailDtoConvertUser(EmailRegisterDto dto) {
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        String saltPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getEmail())
                .email(dto.getEmail())
                .salt(salt)
                .password(saltPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    private void verifyPhoneParam(PhoneRegisterDto dto) {
        // 判断非空
        if (StringUtils.isBlank(dto.getSmsCode())) {
            throw new BussinessException("验证码不可为空！");
        }
        if (StringUtils.isBlank(dto.getPassword())) {
            throw new BussinessException("密码不可为空！");
        }
        if (StringUtils.isBlank(dto.getPasswordRepeat())) {
            throw new BussinessException("确认密码不可为空！");
        }
        // 判断两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 判断验证码是否正确
        String redisSmsCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        String[] split = redisSmsCode.split(":");
        if (StringUtils.isBlank(redisSmsCode) || !split[0].equals(dto.getSmsCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 判断是否注册过
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user) {
            throw new BussinessException("该手机号已被注册！");
        }
    }

    private void verifyEmailParam(EmailRegisterDto dto) {
        // 判断非空
        if (StringUtils.isBlank(dto.getEmailCode())) {
            throw new BussinessException("验证码不可为空！");
        }
        if (StringUtils.isBlank(dto.getPassword())) {
            throw new BussinessException("密码不可为空！");
        }
        if (StringUtils.isBlank(dto.getPasswordRepeat())) {
            throw new BussinessException("确认密码不可为空！");
        }
        // 判断两次密码是否一致
        if (!dto.getPassword().equals(dto.getPasswordRepeat())) {
            throw new BussinessException("两次密码不一致！");
        }
        // 判断验证码是否正确
        String redisEmailCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_EMAILCODE_EMAIL, dto.getEmail()));
        String[] split = redisEmailCode.split(":");
        if (StringUtils.isBlank(redisEmailCode) || !split[0].equals(dto.getEmailCode())) {
            throw new BussinessException("验证码错误！");
        }
        // 判断是否注册过
        User user = userMapper.findByPhone(dto.getEmail());
        if (null != user) {
            throw new BussinessException("该邮箱已被注册！");
        }
    }

}
